package com.feri.openapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.feri.openapi.Util.AliSmsUtil;
import com.feri.openapi.config.RedisKeyConfig;
import com.feri.openapi.dao.SmsDao;
import com.feri.openapi.dto.SmsCodeDto;
import com.feri.openapi.dto.SmsDto;
import com.feri.openapi.entity.Sms;
import com.feri.openapi.model.SmsBean;
import com.feri.openapi.myenum.SmsTemCode;
import com.feri.openapi.redis.RedissionUtils;
import com.feri.openapi.service.SmsService;
import com.feri.openapi.util.RUtils;
import com.feri.openapi.util.RandomNumUtil;
import com.feri.openapi.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Random;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private SmsDao smsDao;


    @Override
    public R sendMsg(SmsDto smsDto) {
        Sms sms = new Sms();
        sms.setFlag(1);
        sms.setRecphone(smsDto.getReceivePhone());
        //发送短信
        /*
        * 1、调用Api
        *
        * */
        if (smsDto.getType()==1){
            //1\生成验证码
            int code= RandomNumUtil.createNum(6);
            sms.setMsg("为："+smsDto.getReceivePhone()+"发送短信验证码："+code);
           String res= AliSmsUtil.sendSms(SmsTemCode.YanZhengMa.getCode(),smsDto.getReceivePhone(),"{\"code\":\""+code+"\"}");//"{\"code\":\""+code+"\"}"
        //2、验证验证码是否发送
            if (res!=null){
                //3、验证验证码发送是否成功
                SmsBean bean= JSON.parseObject(res,SmsBean.class);
                if (Objects.equals(bean.getCode(),"OK")){
                    //发送成功
                    sms.setFlag(2);
                    //存储验证码redis： 有效期 10分钟
                    RedissionUtils.setStr(RedisKeyConfig.SMS_CODE+smsDto.getReceivePhone(),code+"",600);

                }else {
                    sms.setFlag(3);
                }
            }
        }else if (smsDto.getType()==2){
        //推广信息
        }
        //记录数据到数据库
        smsDao.insert(sms);
        return RUtils.setOK();
    }

    @Override
    public R querySms(String phone) {
        return RUtils.setOK(smsDao.queryByPhone(phone));
    }

    @Override
    public R queryPage(int page, int size) {
        return null;
    }

    @Override
    public R checkcode(SmsCodeDto codeDto) {
        //获取之前的验证码 Redis
        if (RedissionUtils.checkKey(RedisKeyConfig.SMS_CODE+codeDto.getPhone())){
            //获取之前的验证码 Redis
            String code = RedissionUtils.getStr(RedisKeyConfig.SMS_CODE + codeDto.getPhone());

            //验证码比较
            if (Objects.equals(code,codeDto.getCode())){
            return RUtils.setOK();
            }else{
                return RUtils.setERROR("验证码输入错误，请检查");
            }

        }else {
            return RUtils.setERROR("验证码失败，请重新获取");
        }
    }
}














